package com.springboot02amqp.amqp;

import com.rabbitmq.client.*;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

@SpringBootTest
public class consumerDemo {

    @Test
    public void consumer() throws IOException, TimeoutException {

        //创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");

        //通过连接工厂创建连接
        Connection connection = factory.newConnection();

        //通过连接创建一个Channel
        Channel channel = connection.createChannel();

        //接收消息的回调函数
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            System.out.println(" 接收到消息: " + new String(message.getBody()));
        };

        //消息中断的回调函数
        CancelCallback cancelCallback = consumerTag -> {
            System.out.println("消息消费被中断：");
        };

        //消费消息，参数1：队列名称, 参数2：是否自动确认, 参数3：接收消息的回调函数, 参数4：消息中断的回调函数
        channel.basicConsume("test_queue", true, deliverCallback, cancelCallback);




    }

}
